from flask import Blueprint, request, jsonify
from models import Device, HeartbeatLog, DeviceLog
import logging

logger = logging.getLogger(__name__)

devices_bp = Blueprint('devices', __name__, url_prefix='/api/devices')


@devices_bp.route('', methods=['GET'])
def get_devices():
    """获取设备列表"""
    try:
        # 获取查询参数
        status = request.args.get('status')  # online/offline/all
        search = request.args.get('search', '')  # 搜索关键词
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 20))
        
        # 构建查询条件
        filters = {}
        if status and status != 'all':
            filters['status'] = status
        
        if search:
            filters['$or'] = [
                {'deviceId': {'$regex': search, '$options': 'i'}},
                {'deviceName': {'$regex': search, '$options': 'i'}}
            ]
        
        # 计算分页
        skip = (page - 1) * page_size
        
        # 查询数据
        devices = Device.find_all(filters, skip=skip, limit=page_size)
        total = Device.count(filters)
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': {
                'list': devices,
                'total': total,
                'page': page,
                'pageSize': page_size
            }
        })
    except Exception as e:
        logger.error(f"获取设备列表失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/<device_id>', methods=['GET'])
def get_device(device_id):
    """获取设备详情"""
    try:
        device = Device.find_by_id(device_id)
        
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': device
        })
    except Exception as e:
        logger.error(f"获取设备详情失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('', methods=['POST'])
def create_device():
    """添加设备"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('deviceId'):
            return jsonify({
                'code': 400,
                'message': '设备ID不能为空'
            }), 400
        
        # 检查设备是否已存在
        existing = Device.find_by_id(data['deviceId'])
        if existing:
            return jsonify({
                'code': 400,
                'message': '设备ID已存在'
            }), 400
        
        # 创建设备
        device = Device.create(data)
        
        # 记录日志
        DeviceLog.create(device['deviceId'], 'config', '设备创建')
        
        return jsonify({
            'code': 200,
            'message': '设备创建成功',
            'data': device
        })
    except Exception as e:
        logger.error(f"创建设备失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/<device_id>', methods=['PUT'])
def update_device(device_id):
    """更新设备信息"""
    try:
        data = request.get_json()
        
        # 检查设备是否存在
        device = Device.find_by_id(device_id)
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        # 不允许更新deviceId
        if 'deviceId' in data:
            del data['deviceId']
        
        # 更新设备
        success = Device.update(device_id, data)
        
        if success:
            # 记录日志
            DeviceLog.create(device_id, 'config', '设备信息更新')
            
            return jsonify({
                'code': 200,
                'message': '设备更新成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '设备更新失败'
            }), 400
    except Exception as e:
        logger.error(f"更新设备失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/<device_id>', methods=['DELETE'])
def delete_device(device_id):
    """删除设备"""
    try:
        # 检查设备是否存在
        device = Device.find_by_id(device_id)
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        # 删除设备
        success = Device.delete(device_id)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '设备删除成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '设备删除失败'
            }), 400
    except Exception as e:
        logger.error(f"删除设备失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/stats', methods=['GET'])
def get_stats():
    """获取设备统计信息"""
    try:
        stats = Device.get_statistics()
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': stats
        })
    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/<device_id>/logs', methods=['GET'])
def get_device_logs(device_id):
    """获取设备日志"""
    try:
        # 检查设备是否存在
        device = Device.find_by_id(device_id)
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        # 获取查询参数
        event_type = request.args.get('eventType')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 50))
        
        # 计算分页
        skip = (page - 1) * page_size
        
        # 查询日志
        logs = DeviceLog.find_by_device(device_id, event_type, skip=skip, limit=page_size)
        total = DeviceLog.count_by_device(device_id, event_type)
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': {
                'list': logs,
                'total': total,
                'page': page,
                'pageSize': page_size
            }
        })
    except Exception as e:
        logger.error(f"获取设备日志失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@devices_bp.route('/<device_id>/heartbeats', methods=['GET'])
def get_device_heartbeats(device_id):
    """获取设备心跳历史"""
    try:
        # 检查设备是否存在
        device = Device.find_by_id(device_id)
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        # 获取查询参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 50))
        
        # 计算分页
        skip = (page - 1) * page_size
        
        # 查询心跳日志
        logs = HeartbeatLog.find_by_device(device_id, skip=skip, limit=page_size)
        total = HeartbeatLog.count_by_device(device_id)
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': {
                'list': logs,
                'total': total,
                'page': page,
                'pageSize': page_size
            }
        })
    except Exception as e:
        logger.error(f"获取心跳历史失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500

